#include <iostream>
#include <string>
#include <cstring>
#include <functional>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <pthread.h>

#include "Log.hpp"
#include "InetAddr.hpp"
#include "Sock.hpp"

class TcpServer;
using namespace socket_ns;

using io_service_t = std::function<void(sock_sptr sockfd, InetAddr client)>;

class ThreadData
{
public:
    ThreadData(sock_sptr fd, InetAddr addr, TcpServer *s) : sockfd(fd), clientaddr(addr), self(s)
    {
    }

public:
    sock_sptr sockfd;
    InetAddr clientaddr;
    TcpServer *self;
};


class TcpServer
{

public:
    TcpServer(int port, io_service_t service) 
        : _localaddr("0",port)
        , _listensock(std::make_unique<TcpSocket>())
        , _service(service)
        , _isrunning(false)
    {
        _listensock->BulidListenSocket(_localaddr);
    }
    
    
    static void *HanderSock(void *args) // IO 和 业务进行解耦
    {
        ThreadData *td = static_cast<ThreadData *>(args);
        td->self->_service(td->sockfd, td->clientaddr);
        ::close(td->sockfd->Sockfd());
        delete td;
        return nullptr;
    }

    void Loop() // 启动 和udp里面的start是一样的
    {
        _isrunning = true;
        // 4、不能直接接受数据，先获取连接
        while (_isrunning)
        {
            // 先接收客户端的连接申请
            InetAddr peerAddr;
            sock_sptr normalsock = _listensock->Accepter(&peerAddr);
            if(normalsock == nullptr) continue;
            // 采用多线程
            pthread_t t;
            ThreadData *td = new ThreadData(normalsock, peerAddr, this);
            pthread_create(&t, nullptr, HanderSock, td);
        }

        _isrunning = false;
    }

    ~TcpServer()
    {}

private:
    InetAddr _localaddr;
    std::unique_ptr<Socket> _listensock; 
    bool _isrunning;

    io_service_t _service;
};

